package com.example.redis.service.ServiceImpl;

import com.alibaba.fastjson.JSON;
import com.example.redis.config.ServiceResultEnum;
import com.example.redis.dao.GoodsMapper;
import com.example.redis.entity.Goods;
import com.example.redis.service.GoodsService;
import com.example.redis.util.PageQueryUtil;
import com.example.redis.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
@Component
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String GOODS_LIST_KEY = "goods:list";
    private static final String GOODS_LIST_KEY_STR = "goods:liststr";

    @Override
    public PageResult getGoodsPage(PageQueryUtil pageUtil){
        //查询缓存
        Long count = redisTemplate.opsForList().size(GOODS_LIST_KEY);
        int currentPage = pageUtil.getPage();
        int pageSize = pageUtil.getLimit();
        int total = count.intValue();
        int start = (currentPage - 1) * pageSize;
        int end = start + pageSize -1;
        //判断有没有缓存
        if(count == 0){
            String goodsStrList = stringRedisTemplate.opsForValue().get(GOODS_LIST_KEY_STR);
            // 缓存中存在商品列表，将 JSON 字符串转换为对象
            List<Goods> goodsList = JSON.parseArray(goodsStrList, Goods.class);
            List<Goods> list = redisTemplate.opsForList().range(GOODS_LIST_KEY_STR, start, end);
            PageResult pageResult = new PageResult(list, total, pageUtil.getLimit(), pageUtil.getPage());
            if(list != null) {
                //把对象转json字符串
//                String pageResultJson = JSON.toJSONString(list);
                //添加缓存
//               stringRedisTemplate.opsForList().rightPushAll(GOODS_LIST_KEY, pageResultJson);
                redisTemplate.opsForList().rightPushAll(GOODS_LIST_KEY,goodsList);
                return pageResult;
            }
        } else {
            List<Goods> list = redisTemplate.opsForList().range(GOODS_LIST_KEY, start, end);
            PageResult pageResult = new PageResult(list, total, pageUtil.getLimit(), pageUtil.getPage());
            //字符串转对象
            //PageResult pageResult = JSON.parseObject(goodsString,PageResult.class);
            return pageResult;
    }
        return null;
    }

    @Override
    public List<Goods> getFirstGoods(){
        //查询缓存
        Long count = redisTemplate.opsForList().size(GOODS_LIST_KEY);
        if(count == 0 ){
            String goodsStrList = stringRedisTemplate.opsForValue().get(GOODS_LIST_KEY_STR);
            List<Goods> goodsList = JSON.parseArray(goodsStrList, Goods.class);
            Goods good = goodsList.get(goodsList.size()-1);
            List<Goods> goods = new ArrayList<>();
            goods.add(good);
            return goods;
        }else {
            List<Goods> goods = redisTemplate.opsForList().range(GOODS_LIST_KEY, count-1,count-1);
            return goods;
        }
//        return goodsMapper.selectByDesc();
    }

    @Override
    public Boolean deleteBatch(Long[] ids){

        for(int i = 0;i<ids.length ;i++) {
            redisTemplate.opsForList().remove(GOODS_LIST_KEY,0,redisTemplate.opsForList().index(GOODS_LIST_KEY,ids[i]));
        }

        return goodsMapper.deleteBatch(ids) > 0;
    }

    @Override
    public String saveGoods(Goods goods) {
        //查询缓存
        Long count = redisTemplate.opsForList().size(GOODS_LIST_KEY);
        goods.setId(count+1);
        if ((redisTemplate.opsForList().rightPush(GOODS_LIST_KEY, goods) > 0)
                &&(goodsMapper.insertSelective(goods)>0)) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
//        if (goodsMapper.insertSelective(goods) > 0) {
//
//        }
//
    }


    @Override
    public String updateGoods(Goods goods){
        Goods temp = goodsMapper.selectByPrimaryKey(goods.getId());
        if(temp == null){
            return ServiceResultEnum.DATA_NOT_EXIST.getResult();
        }
        redisTemplate.opsForList().set(GOODS_LIST_KEY,goods.getId(),goods);
        if((goodsMapper.updateByPrimaryKeySelective(goods) > 0)){
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    @Override
    public Goods getById(Long id){
        //查询缓存
        String goodsString = stringRedisTemplate.opsForValue().get("goods:"+id);
        System.out.println(goodsString);
        //判断有没有缓存
        if(StringUtils.isEmpty(goodsString)){
            //从数据库查询商品信息
            Goods goods = goodsMapper.selectByPrimaryKey(id);
            if(goods != null){
                //把对象转json字符串
                String goodsJson = JSON.toJSONString(goods);
                //添加缓存
                stringRedisTemplate.opsForValue().set("goods:"+ id,goodsJson);
                return goods;
            }
        }else {
            //字符串转对象
            Goods goods = JSON.parseObject(goodsString,Goods.class);
            return goods;
        }
        return null;
    }

    @Scheduled(cron = "0 */30 * * * ?")
    public void loadActivityProduct() {
        System.out.println("-------");
        //从数据库中查询参加活动的商品列表
        List<Goods> goodsList = goodsMapper.findAllGoods();
        //先缓存一份String类型的数据，直接set，如果要分页则解析成list再返回
        redisTemplate.opsForValue().set(GOODS_LIST_KEY_STR, JSON.toJSONString(goodsList));
        //删除旧的
        redisTemplate.delete(GOODS_LIST_KEY);
        //存储新的
        redisTemplate.opsForList().rightPushAll(GOODS_LIST_KEY, goodsList);
    }

}
